<template>
  <scroll-view class="apply-wrapper" :scroll-y="true">
    <view class="inner-wrapper">
      <XqFormBuild
        v-if="isShow"
        ref="form"
        :dynamicData="dynamicData"
        :form="form"
        :formConfig="formConfig"
        :rules="rules"
        :selectMap="selectMap"
        :tempData="tempData"
        @update="onFormUpdate"
      />
      <view v-if="flowNodes.length > 0">
        <template v-for="(item, index) in flowNodes">
          <view
            v-if="item.nodeType === 'task'"
            :key="index"
            class="form-approval-item column"
          >
            <view
              class="form-approval-item-label"
              :class="{ disabled: !item.isOptional }"
            >{{ item.name }}({{ getType(item.activateType) }})</view>
            <view
              class="form-approval-item-content"
              :class="{ disabled: !item.isOptional }"
            >
              <Approver
                :is-flow="true"
                :tabs="getTabs(item.chooseRange)"
                :range="item.choosePersons"
                :multiple="item.chooseIsMulti"
                :disabled="!item.isOptional"
                :value="getIds(item.roleIdShow, item.userIdShow)"
                :placeholder="`请选择${item.name}`"
                @change="onEmployeeChange($event, index)"
              />
            </view>
          </view>
          <view
            v-else-if="item.nodeType === 'notifier'"
            :key="index"
            class="form-approval-item column"
          >
            <view
              class="form-approval-item-label"
              :class="{ disabled: !item.isOptional }"
            >{{ item.name }}</view>
            <view
              class="form-approval-item-content"
              :class="{ disabled: !item.isOptional }"
            >
              <Approver
                :is-flow="true"
                :tabs="getTabs(item.chooseRange)"
                :range="item.choosePersons"
                :multiple="item.chooseIsMulti"
                :disabled="!item.isOptional"
                :value="getIds(item.roleIdShow, item.userIdShow)"
                :placeholder="`请选择${item.name}`"
                @change="onEmployeeChange($event, index)"
              />
            </view>
          </view>
        </template>
        <button :disabled="loading" class="apply-btn" @tap="onSubmitApproval">
          提交审批
        </button>
      </view>
    </view>
  </scroll-view>
</template>
<script>
import XqFormBuild from "@/components/XqForm/XqFormBuild/index";
import { buildForm, handleTailValue } from "@/components/XqForm/utils";
import { getFlowReq, getFlowProcessByApproInfoReq, submitApprovalReq } from "@/services/employee";
import Approver from "./FormBuild/components/Approver";
import _ from "lodash";
export default {
  components: {
    XqFormBuild,
    Approver
  },
  props: {},
  data() {
    return {
      flow_id: null,
      flowNodes: [],
      fields: [],
      loading: false,
      isShow: false,
      formData: {},
      dynamicData: {},
      form: null,
      formConfig: null,
      rules: null,
      selectMap: null,
      tempData: {}
    }
  },
  computed: {
    formValues() {
      if (this && this.form) {
        const formValues = this.fields.map(item => ({
          formId: item.id,
          value: this.form[item.code]
        }));
        return formValues;
      }
      return [];
    }
  },
  onLoad(options) {
    this.flow_id = options.id;
    this.getFlow(this.flow_id);
  },
  methods: {
    onEmployeeChange(val, idx) {
      const res = Object.assign({}, this.flowNodes[idx], val);
      this.flowNodes[idx] = res;
    },
    onSubmitApproval() {
      this.loading = true;
      submitApprovalReq({
        flowId: this.flow_id,
        userApproInfoList: this.formValues,
        flowNodeList: this.flowNodes
      })
        .then(res => {
          const timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 2000);
          uni.showToast({
            title: "审批提交成功",
            icon: "none",
            duration: 2000
          });
          setTimeout(() => {
            uni.redirectTo({
              url: "/approval/index?tab=1"
            });
          }, 1000);
        })
        .catch(err => {
          const timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 2000);
          console.log("debug log --> ", err);
        });
    },
    onFormUpdate: _.throttle(function(tail, value){
      handleTailValue(tail, value, this);
      if (this && this.form) {
        getFlowProcessByApproInfoReq({
            flowId: this.flow_id,
            userApproInfoList: this.formValues
          })
            .then(res => {
              this.flowNodes = res;
            })
            .catch(err => {
              console.log("debug log --> ", err);
            });
      }
    }, 1000),
    getFlow(flow_id) {
      uni.showLoading({
        title: "表单加载中..."
      });
      getFlowReq(flow_id)
        .then(res => {
          if (res && res.length > 0) {
            this.fields = res;
            const fieldMap = {};
            for (let i = 0; i < res.length; i++) {
              const item = JSON.parse(res[i]["props"]);
              fieldMap[item["model"]] = item;
            }
            const { form, formConfig, rules, selectMap } = buildForm(fieldMap);
            this.form = form;
            this.formConfig = formConfig;
            this.rules = rules;
            this.selectMap = selectMap;
            this.isShow = true;
            this.$nextTick(() => {
              this.$refs.form.init();
            });
          } else {
              uni.showToast({
              title: "没有要填写的内容",
              icon: "none",
              duration: 2000
            });
          }
          uni.hideLoading();
        })
        .catch(err => {
          uni.hideLoading();
          uni.showToast({
            title: err.message,
            icon: "none",
            duration: 2000
          });
        });
    },
    getTabs(range) {
      switch (range) {
        case "allUserAndRole":
          return ["employee", "admin", "role"];
        case "allUser":
          return ["employee", "admin"];
        case "limitUser":
          return ["employee"];
        case "allRole":
          return ["role"];
        case "limitRole":
          return ["role"];
        case "all":
          return ["employee", "admin", "role"];
        case "designated":
          return ["employee"];
        case "role":
          return ["role"];
        case "roleUser":
          return ["admin"];
        default:
          return [];
      }
    },
    getIds(roleIds, userIds) {
      let res = "";
      if (!!roleIds) {
        res = res + roleIds;
      }
      if (!!userIds) {
        if (!!res) {
          res = res + "," + userIds;
        } else {
          res = userIds;
        }
      }
      return res;
    },
    getType(key) {
      return ["依次审批", "会签", "或签"][key];
    }
  }
}
</script>